#include <dbhandler.h>

int ShowCallback(void *data, int columns, char** array, char** col_name);

bool DbHandler::SetDbPath(const char *str){
    using namespace std;
    //检查字符串结尾是否为.db
    string s = str;
    if (s.find(".db") == string::npos)return false;
    std::strcpy(dbpath, str);
    return true;
}

void DbHandler::CloseDb(){
    sqlite3_close(sql);
}



bool DbHandler::OpenDb(){
    if(dbpath == "")return false;
    return sqlite3_open(dbpath, &sql);
}

void DbHandler::CreateTable(const char *sql_lan){
    char *err_msg = 0;
    int rc = sqlite3_exec(sql, sql_lan, nullptr, 0, &err_msg);
    if (rc != SQLITE_OK){
        cout << "SQL error: " << err_msg << '\n';
        sqlite3_free(err_msg);
    }
}

int DbHandler::InsertTableItem(const char *sql_lan){
    char *err_msg = 0;
    int rc = sqlite3_exec(sql, sql_lan, nullptr, 0, &err_msg);
    if (rc != SQLITE_OK) {
        cout << "SQL error: " << err_msg << '\n';
        sqlite3_free(err_msg);
    }
    return rc;
}

int DbHandler::SelectTableItem(string table, string item, string condition , int (*callback)(void*,int,char**, char**), void* data){
    string sql_lan = "";
    if(condition == ""){
        sql_lan = "select " + item + " from " + table + ";";
        cout << sql_lan << endl;
    }else {
        sql_lan = "select " + item + " from " + table + " where " + condition + ";";
        cout << sql_lan << endl;
    }

    char *err_msg = 0;
//    int rc = sqlite3_exec(sql, sql_lan.c_str(), ShowCallback, 0, &err_msg);
    int rc = sqlite3_exec(sql, sql_lan.c_str(), callback, data, &err_msg);
    if (rc != SQLITE_OK) {
        cout << "SQL error: " << err_msg << '\n';
        sqlite3_free(err_msg);
    }
    return rc;
}



void DbHandler::DeleteTableItem(string table, string delete_item){
    string sql_lan = "DELETE FROM " + table + " WHERE " + delete_item +";";

    char *err_msg = 0;
    int rc = sqlite3_exec(sql, sql_lan.c_str(), ShowCallback, 0, &err_msg);
    if (rc != SQLITE_OK) {
        cout << "SQL error: " << err_msg << '\n';
        sqlite3_free(err_msg);
    }
}

void DbHandler::UpdateTableItem(string table, string set_item, string where){
    string sql_lan = "UPDATE " + table + " SET " + set_item + " Where " + where;

    char *err_msg = 0;
    int rc = sqlite3_exec(sql, sql_lan.c_str(), ShowCallback, 0, &err_msg);
    if (rc != SQLITE_OK) {
        cout << "SQL error: " << err_msg << '\n';
        sqlite3_free(err_msg);
    }
}

int ShowCallback(void *data, int columns, char** array, char** col_name){
    for (int i = 0; i < columns; i++){
        cout << col_name[i] << ": "<< array[i] << '\n';
    }
    return SQLITE_OK;
}

